﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SmartSpace.Vote;

namespace SmartSpace.Vote.AjaxPage
{
    public partial class AjaxVote : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            String tag = Request["tag"] ?? String.Empty;
            if (tag=="add")
            {
                Guid id = new Guid();
                SaveTheme(id);
            }
            if (tag=="edit")
            {
                string id = Request["id"] ?? string.Empty;
                SaveTheme(new Guid(id));
            }
            if (tag=="getallthemes")
            {
                GetAllThemes();
            }
            if (tag=="updatecount")
            {
                UpdateVote();
            }
        }

        private void UpdateVote()
        {
            string msg = "";
            
            string id = Request["id"] ?? string.Empty;
            string[] ids = id.Split(',');

            VoteServices s = new VoteServices();
            VoteTheme v = new VoteTheme();

            for (int i = 0; i < ids.Length; i++) {
                SingleResult<VoteTheme> re = s.GetVoteTheme(new Guid(ids[i]));

                if (re.IsSuccess)
                {
                    v = re.Data;
                    ServiceResult r = s.SaveVoteTheme(v);

                    if (r.IsSuccess != true)
                    {
                        msg += ids[i] + "update vote count error!";
                    }
                }
            }

            if (msg != "")
            {
                Response.Write("1-" + msg);
            }
            else
            {
                Response.Write("0-update vote count all success");
            }
        }

        private void GetAllThemes()
        {
            VoteServices s = new VoteServices();
            Response.Write(Common.DataTableToJson(s.GetAllThemes()));
        }

        private void SaveTheme(Guid id)
        {
            VoteServices s = new VoteServices();
            VoteTheme v = new VoteTheme();
            v.Id = id;
            v.Name = Request["name"] ?? string.Empty;
            v.Discription = Request["discription"] ?? string.Empty;
            v.Code = Request["code"] ?? string.Empty;
            v.ImgUrl = Request["img"] ?? string.Empty;
            v.ThemeType = Convert.ToInt32(Request["type"] ?? string.Empty);

            ServiceResult r = s.SaveVoteTheme(v);
            if (r.IsSuccess == true)
            {
                Response.Write("0-Save Success");
            }
            else
            {
                Response.Write("1-Save Error");
            }
        }
    }
}